<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="65%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="200px"
      v-loading="formLoading"
    >
      <el-divider>基础信息</el-divider>
      <el-row>
        <el-col :span="24">
          <el-button plain type="primary" @click="openTargetsCustomerDialog"
            >拓展客户导入</el-button
          >
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入客户名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户编号" prop="code">
            <el-input v-model="formData.code" placeholder="请输入客户编号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户原名" prop="preName">
            <el-input v-model="formData.preName" placeholder="请输入客户原名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="管理单位" prop="manageUnit">
            <el-input v-model="formData.manageUnit" placeholder="请输入管理单位" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属区域" prop="area">
            <el-cascader
              v-model="formData.area"
              :options="areaList"
              :props="defaultProps"
              class="w-1/1"
              clearable
              filterable
              placeholder="请选择所属区域"
            />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="定位" prop="position">
            <el-input v-model="formData.position" placeholder="请输入定位" />
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-button plain type="primary" @click="openBaiduMapDialog">定位</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="地址" prop="address">
            <el-input v-model="formData.address" placeholder="请输入地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="行业分类" prop="industry">
            <el-select v-model="formData.industry" placeholder="请选择行业分类">
              <el-option-group
                v-for="group in IndustryTypeOptionsGroup"
                :key="group.label"
                :label="group.label"
              >
                <el-option
                  v-for="item in group.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-option-group>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系人姓名" prop="contactName">
            <el-input v-model="formData.contactName" placeholder="请输入联系人姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactNumber">
            <el-input v-model="formData.contactNumber" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系人职务" prop="contactDuty">
            <el-input v-model="formData.contactDuty" placeholder="请输入联系人职务" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人年龄" prop="contactAge">
            <el-select v-model="formData.contactAge" placeholder="请选择联系人年龄" class="w-1/1">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_CUSTOMER_ARCHIVE_CONTACT_AGE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="简介" prop="introduce">
            <el-input type="textarea" v-model="formData.introduce" placeholder="请输入简介" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider>其他信息</el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="业务来源" prop="businessSource">
            <el-select v-model="formData.businessSource" placeholder="请选择业务来源">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_EXPAND_BUSINESS_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司规模" prop="companyScale">
            <el-select v-model="formData.companyScale" placeholder="请选择公司规模">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CRM_CUSTOMER_COMPANY_SIZE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户需求" prop="customerRequire">
            <el-select
              v-model="formData.customerRequire"
              placeholder="请选择客户需求"
              class="w-1/1"
              multiple
            >
              <el-option-group
                v-for="group in CustomerApi.customerDemandOptionsGroup"
                :key="group.label"
                :label="group.label"
              >
                <el-option
                  v-for="item in group.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-option-group>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用电场景" prop="powerScene">
            <el-select v-model="formData.powerScene" placeholder="请选择用电场景">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CRM_CUSTOMER_ELECTRICITY_USAGE_SCENARIO)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="签约难度" prop="signDifficulty">
            <el-select v-model="formData.signDifficulty" placeholder="请选择签约难度">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CRM_CUSTOMER_SIGNING_DIFFICULTY)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收款难度" prop="receiveDifficulty">
            <el-select v-model="formData.receiveDifficulty" placeholder="请选择收款难度">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CRM_CUSTOMER_COLLECT_PAYMENT_DIFFICULTY)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="决策人名称" prop="directorName">
            <el-input v-model="formData.directorName" placeholder="请输入决策人名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="决策人电话" prop="directorNumber">
            <el-input v-model="formData.directorNumber" placeholder="请输入决策人电话" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="决策人职务" prop="directorDuty">
            <el-input v-model="formData.directorDuty" placeholder="请输入决策人职务" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="决策人年龄" prop="directorAge">
            <el-select v-model="formData.directorAge" placeholder="请选择决策人年龄">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_CUSTOMER_ARCHIVE_CONTACT_AGE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="对电力行业了解程度" prop="powerIndustryKnown">
            <el-select v-model="formData.powerIndustryKnown" placeholder="请选择对电力行业了解程度">
              <el-option
                v-for="dict in getStrDictOptions(
                  DICT_TYPE.CRM_CUSTOMER_INDUSTRY_UNDERSTANDING_LEVEL
                )"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="对电费单、用电知识了解程度" prop="powerKnowledge">
            <el-select
              v-model="formData.powerKnowledge"
              placeholder="请选择对电费单、用电知识了解程度"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CRM_CUSTOMER_KNOWLEDGE_LEVEL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="特殊情况记录" prop="specialRemark">
            <el-input
              type="textarea"
              v-model="formData.specialRemark"
              placeholder="请输入特殊情况记录"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <ExpandTargetsCustomerDialog ref="targetsCustomerDialogRef" @success="handleSelectedCustomer" />
  <BaiduMap ref="baiduMapDialogRef" @success="handleBaiduMapPosition" />
</template>
<script setup lang="ts">
import { CustomerArchiveApi, CustomerArchive } from '@/api/biz/customer'
import ExpandTargetsCustomerDialog from './ExpandTargetsCustomerDialog.vue'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { IndustryTypeOptionsGroup } from '@/api/biz/expand/targets/partner'
import * as CustomerApi from '@/api/crm/customer'
import { useUserStore } from '@/store/modules/user'
import { defaultProps } from '@/utils/tree'
import * as AreaApi from '@/api/system/area'

import BaiduMap from '../component/BaiduMap.vue'

/** 客户档案 表单 */
defineOptions({ name: 'CustomerArchiveForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  code: undefined,
  preName: undefined,
  manageUnit: undefined,
  area: undefined,
  position: undefined,
  address: undefined,
  industry: undefined,
  contactName: undefined,
  contactNumber: undefined,
  contactDuty: undefined,
  contactAge: undefined,
  introduce: undefined,
  businessSource: undefined,
  companyScale: undefined,
  customerRequire: undefined,
  powerScene: undefined,
  signDifficulty: undefined,
  receiveDifficulty: undefined,
  directorName: undefined,
  directorNumber: undefined,
  directorDuty: undefined,
  directorAge: undefined,
  powerIndustryKnown: undefined,
  powerKnowledge: undefined,
  specialRemark: undefined,
  ownerUserId: undefined,
  expandTargetCustomerId: undefined
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref
const areaList = ref([]) // 地区列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()
  // 获取当期用户id
  formData.value.ownerUserId = useUserStore().getUser.id

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CustomerArchiveApi.getCustomerArchive(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CustomerArchive
    if (formType.value === 'create') {
      await CustomerArchiveApi.createCustomerArchive(data)
      message.success(t('common.createSuccess'))
    } else {
      await CustomerArchiveApi.updateCustomerArchive(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    code: undefined,
    preName: undefined,
    manageUnit: undefined,
    area: undefined,
    position: undefined,
    address: undefined,
    industry: undefined,
    contactName: undefined,
    contactNumber: undefined,
    contactDuty: undefined,
    contactAge: undefined,
    introduce: undefined,
    businessSource: undefined,
    companyScale: undefined,
    customerRequire: undefined,
    powerScene: undefined,
    signDifficulty: undefined,
    receiveDifficulty: undefined,
    directorName: undefined,
    directorNumber: undefined,
    directorDuty: undefined,
    directorAge: undefined,
    powerIndustryKnown: undefined,
    powerKnowledge: undefined,
    specialRemark: undefined,
    ownerUserId: undefined,
    expandTargetCustomerId: undefined
  }
  formRef.value?.resetFields()
}

/** 打开拓展客户列表 */
const targetsCustomerDialogRef = ref()
const openTargetsCustomerDialog = () => {
  targetsCustomerDialogRef.value.open()
}

const handleSelectedCustomer = (customerData) => {
  if (customerData !== undefined) {
    formData.value.name = customerData.customerName
    formData.value.contactName = customerData.contactName
    formData.value.contactNumber = customerData.contactNumber
    formData.value.businessSource = customerData.businessResource
    formData.value.address = customerData.address
    formData.value.expandTargetCustomerId = customerData.id
  }
}

/** 打开百度地图 */
const baiduMapDialogRef = ref()
const openBaiduMapDialog = () => {
  baiduMapDialogRef.value.open()
}
const handleBaiduMapPosition = (addressInfo) => {
  if (addressInfo !== undefined) {
    formData.value.position =
      addressInfo.longitude.toFixed(4) + ',' + addressInfo.latitude.toFixed(4)
  }
}
</script>
